package com.huixi.service.impl;

import com.huixi.entity.Item;
import com.huixi.service.CartService;
import com.huixi.service.mapper.ItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service(value = "cartService")
public class CartServiceImpl implements CartService {

    private static final String REDIS_CART_PRE = "CART";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ItemMapper itemMapper;

    //购物车添加商品
    @Override
    public void addCart(Long userId, Long itemId, int num) {
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        String key = REDIS_CART_PRE + ":" + userId;
        Boolean isExist = hashOperations.hasKey(key, itemId);
        //redis中存在该商品信息
        if (isExist) {
            Item item = (Item) hashOperations.get(key, isExist);
            //累计添加数量
            item.setNum(item.getNum() + num);
            hashOperations.put(key, itemId, item);
        }

        Item item = itemMapper.selectById(itemId);
        item.setNum(num);
        hashOperations.put(key, itemId, item);
    }


    //合并购物车
    public void mergeCart(Long userId, List<Item> itemList) {
        for (Item item : itemList) {
            addCart(userId, item.getId(), item.getNum());
        }
    }


    //获取购物车列表
    public List<Item> getCartList(Long userId) {
        String key = REDIS_CART_PRE + ":" + userId;
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        List<Object> values = hashOperations.values(key);
        List<Item> itemList = new ArrayList<>(values.size());
        for (Object object : values) {
            itemList.add((Item) object);
        }

        return itemList;
    }


    public void updateCartNum(Long userId, Long itemId, int num) {
        String key = REDIS_CART_PRE + ":" + userId;
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        Item item = (Item) hashOperations.get(key, itemId);
        item.setNum(num);
        hashOperations.put(key, item, item);
    }


    //删除购物车商品
    public void deleteCartItem(Long userId, Long itemId) {
        String key = REDIS_CART_PRE + ":" + userId;
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, itemId);
    }

    //清空购物车
    public void clearCartItem(Long userId) {
        String key = REDIS_CART_PRE + ":" + userId;
        redisTemplate.delete(key);
    }

}
